const mongoose = require('mongoose');
const rp=require("request-promise")
const get = async ({ curpage, eachPage }) => {
    const result = {
        curpage: ~~curpage,
        eachPage: ~~eachPage,
        total: 0,
        maxPage: 0,
        rows: []
    }
    const cinemasModel = mongoose.model("cinemas")
    result.total = await cinemasModel.countDocuments();
    result.maxPage = Math.ceil(result.total / result.eachPage)
    result.rows = await cinemasModel
        .find()
        .skip((result.curpage - 1) * result.eachPage)
        .limit(result.eachPage)
        .exec()
    return result
}
const xin = async (cinemas) => {
    const modelcinemas = mongoose.model("cinemas").create(cinemas);
    return await modelcinemas;
}
const getOne = async _id => {
    const cinemasModel = mongoose.model("cinemas");
    return await cinemasModel.findOne({ _id });
}
const addImgs = async ({ _id, url }) => {
    const cinemasModel = mongoose.model("cinemas");
    return await cinemasModel.updateOne(
        { _id },
        {
            $push: {
                imgs: url
            }
        })
}
const deleteimg = async ({ _id, url }) => {
    const cinema = await getOne(_id);
    cinema.imgs.pull(url);
    await cinema.save();
    var options = {
        method: "DELETE",
        url: `http://localhost:3002/cinemas/${_id}/imgs/${encodeURIComponent(url)}`,
        json: true
    };
    return await rp(options);
}
const xiu = async ({ _id, name, phone, address, status }) => {
    const modelcinemas = mongoose.model("cinemas").updateOne({ _id: _id },
        {
            $set: {
                name: name,
                phone: phone,
                address: address,
                status: status,
            }
        })
    return await modelcinemas;
}
const shan = async ({ _id, name, phone, address, status, imgs }) => {
    const modelcinemas = mongoose.model("cinemas").remove({ _id: _id },
        {
            $set: {
                name: name,
                phone: phone,
                address: address,
                status: status,
                imgs: imgs,
            }
        })
    return await modelcinemas;
}
const cha = async ({ name, address, status }) => {
    const cinemasModel = mongoose.model("cinemas");
    return await cinemasModel.find({
        name: {
            $regex: String(name)
        },
        address: {
            $regex: String(address)
        },
        status: status,
        // status: {
        //     $regex: Boolean(status)
        // },
    });
}
module.exports = { get, xin, getOne, addImgs, xiu, shan, cha, deleteimg }
